<?php

namespace backend\models;

use Yii;

/**
 * This is the model class for table "baseprivilege".
 *
 * @property int $RoleId 角色标识
 * @property int $ModuleId 模块标识
 */
class Baseprivilege extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'baseprivilege';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['RoleId', 'ModuleId'], 'required'],
            [['RoleId', 'ModuleId'], 'integer'],
            [['RoleId', 'ModuleId'], 'unique', 'targetAttribute' => ['RoleId', 'ModuleId']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'RoleId' => '角色标识',
            'ModuleId' => '模块标识',
        ];
    }

    public function getModules($roleid)
    {
        $color = ['green','blue','indigo','purple','pink','orange','red','yellow','teal','cyan','gray','gray-dark','gradient-yellow-green','gradient-cyan-purple'];
        $icon = ['home','users','user','trademark','money-bill-alt','shopping-basket','beer','cog','heading','chart-bar','street-view','paw'];
        $sql = "select * 
                from baseprivilege as bp 
                inner join basemodule as bm on bp.ModuleId = bm.Id 
                where bp.RoleId = {$roleid} and bm.ClassId < 2 and bm.Pid = 0 order by bm.SortId asc ";
        $data = yii::$app->db->createCommand($sql)->queryAll();
        foreach ($data as $key => $val){
            $sqla = "select * 
                     from basemodule m 
                     right join baseprivilege p on m.Id = p.ModuleId 
                     where m.Pid = {$val['ModuleId']} and m.ClassId = 1 and p.RoleId = {$roleid} order by m.SortId asc ";
            $data[$key]['Children'] = yii::$app->db->createCommand($sqla)->queryAll();
            $data[$key]['color'] = $color[$key];
            $data[$key]['icon'] = $icon[$key];
        }
        return $data;
    }


    public function getNode($rid)
    {
        $sql = "select *,(select ModuleId from baseprivilege where RoleId={$rid} and ModuleId = Id) as ssid
                from basemodule";
        $data = yii::$app->db->createCommand($sql)->queryAll();
        return self::_generateTree($data);
    }

    private static function _generateTree ($data, $pid = 0) {
        $tree = [];
        if ($data && is_array($data)) {
            foreach($data as $k => $v) {
                $check['checked'] = false;
                if ($v['ssid'] == $v['Id']){
                    $check['checked'] = true;
                }
                if($v['Pid'] == $pid) {
                    $tags = empty($v['ClassId']) ? "<i class='text-primary'>系统模块</i>" : (($v['ClassId'] == 1) ? "<i class='text-rose'>导航菜单</i>" : "<i class='text-gray'>执行动作</i>");
                    $tree[] = [
                        'id' => $v['Id'],
                        'pid' => $v['Pid'],
                        'href' => $v['RouteURL'],
                        'ClassId' => $v['ClassId'],
                        'text' => $v['Title'],
                        'nodes' => self::_generateTree($data, $v['Id']),
                        'tags' => [$tags],
                        'state' => $check,
                    ];
                }
            }
        }
        if (empty($tree)){
            $tree = '';
        }
        return $tree;
    }


    /**
     * 保存权限角色数据
     */
    public function savePrivilege($postdata)
    {
        $roleId = $postdata['rid'];
        $ids = $postdata['ids'];
        $ids = explode(',', $ids);
        try{
            self::deleteAll(['RoleId'=>$roleId]);
            foreach ($ids as $id) {
                yii::$app->db->createCommand()->insert('baseprivilege',['RoleId'=>$roleId, 'ModuleId'=>$id])->execute();
            }
        }catch (\Exception $e){
            return ['statusCode' => 300, 'message'=> '保存角色模块权限失败'];
        }
        return ['statusCode' => 200, 'message'=> '已成功保存角色模块权限'];
    }


}
